package com.tnsw.facebookautoliker;

import com.facebook.Session;
import com.tnsw.coreutils.MyLog;
import com.tnsw.facebookautoliker.base.FragmentBase;
import com.tnsw.facebookautoliker.database.DBManager;
import com.tnsw.facebookautoliker.database.SelfInfo;
import com.tnsw.facebookautoliker.helper.FacebookActionListener;
import com.tnsw.facebookautoliker.helper.FacebookBGManager;
import com.tnsw.facebookautoliker.helper.FacebookCommandObject;
import com.tnsw.facebookautoliker.helper.command.GetHTTPPhoto;
import com.tnsw.facebookautoliker.helper.command.GetPhoto;
import com.tnsw.facebookautoliker.helper.command.GetSelfInfo;
import com.tnsw.facebookautoliker.services.AutoLikerService;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnScrollChangedListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.TextView;

public class MyselfFragment extends FragmentBase implements OnClickListener, FacebookActionListener, OnCheckedChangeListener {

	private Context context;
	private LayoutInflater inflater=null;
	private ViewGroup root;
	
	private FacebookBGManager fbm;
	private DBManager dbm;
	
	private TextView tvName, tvUsername;
	private ImageView imgSelfPhoto;
	private MySwitcher swLikeUpdateStatus, swLikeUpdatePhoto, swLikeSharePhoto, swLikeShareVideo;
	private MySwitcher swLikeShareStory, swLikeChangeProfilePhoto, swLikeTagPhoto, swLikeUploadVideo, swLikeFromOther;
	private Switch swAutoLike;
	
	private SelfInfo selfinfoRecord;
	
	private LoadingDialog dlgLoading;
	private LinearLayout linearScroll;
	private ScrollView vScrollView;

	public MyselfFragment() {		
		super();
		this.tag = "MyselfFragment";
		//this.setHasOptionsMenu(true);
		
		this.context = this.getActivity();
		if (this.context != null) {
			MyLog.d(tag, "Can get Context from this.getActivity()");
		} else {
			MyLog.d(tag, "!! Cannot get Context from this.getActivity()");
		}
		
	}
		
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyLog.d(tag, "onCreate()");
		if (this.getActivity() != null) {
			MyLog.d(tag, "Got context now");
			
			this.context = this.getActivity();
			
			this.fbm = FacebookBGManager.getInstance(context);
			this.fbm.registerActionListener(this);
			
			this.dbm = DBManager.getInstance(context);
			
			this.dlgLoading = new LoadingDialog();
			this.dlgLoading.setCancelable(false);
		} else {
			MyLog.d(tag, "Still cannot get context");
		}
		
	}
	
	@Override
	public void onStart() {
		super.onStart();
		MyLog.d(tag, "onStart()");
	}
	
	@Override
	public void onResume() {
		super.onResume();
		AutoLikerService aService = AutoLikerService.getInstance();
		
		if (this.getLastCommand() == null) {
			
			if ( (aService != null) && (aService.getSelfInfo() != null) ) {
				this.selfinfoRecord = aService.getSelfInfo();
				MyLog.d(tag, "using self_info from AutoLikerService");
			} else {
				this.selfinfoRecord = (SelfInfo) this.dbm.getSingleRecordByPrimarykey(SelfInfo.class.getName(), "self_info", 1);	
				aService.setSelfInfo(this.selfinfoRecord);
				MyLog.d(tag, "using self_info from database and put the value to AutoLikerService");
			}
			
			if (this.selfinfoRecord == null) {
				MyLog.d(tag, "Cannot find pk=1 in self_info, calling FBAPI to get info first");
				GetSelfInfo selfInfo = new GetSelfInfo(this.context);
				selfInfo.setParentFragmentBase(this);
				selfInfo.execute();	
			} else {
				MyLog.d(tag, "Found self_info..");
				this.tvName.setText(this.selfinfoRecord.name);
				this.tvUsername.setText(this.selfinfoRecord.username);
				this.imgSelfPhoto.setImageBitmap(BitmapFactory.decodeFile(this.selfinfoRecord.photo_path));
				
				this.updateSwitchesStatus();
			}
			
		} else {
			MyLog.d(tag, "Executing last command because last time failed");
			this.executeLastCommand();
		}
		
	}
	
	@Override
	public void onPause() {
		super.onPause();
		MyLog.d(tag, "onPause()");
	}
	
	@Override
	public void onStop() {
		super.onStop();
		MyLog.d(tag, "onStop()");
	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		MyLog.d(tag, "onDestroyView()");
		
	}
	
	@Override
	public void onDestroy () {
		super.onDestroy();
		MyLog.d(tag, "onDestroy()");
	}
	
	@Override
	public void onDetach() {
		super.onDetach();
		MyLog.d(tag, "onDetach()");
		this.fbm.unregisterActionListener(this);
	}
	
	private void updateSwitchesStatus() {
		this.swLikeUpdatePhoto.updateSwitchStatus(this.selfinfoRecord);
		this.swLikeUpdateStatus.updateSwitchStatus(this.selfinfoRecord);
		this.swLikeSharePhoto.updateSwitchStatus(this.selfinfoRecord);
		this.swLikeShareVideo.updateSwitchStatus(this.selfinfoRecord);
		this.swLikeShareStory.updateSwitchStatus(this.selfinfoRecord);
		this.swLikeTagPhoto.updateSwitchStatus(this.selfinfoRecord);
		this.swLikeUploadVideo.updateSwitchStatus(this.selfinfoRecord);
		this.swLikeChangeProfilePhoto.updateSwitchStatus(this.selfinfoRecord);
		this.swLikeFromOther.updateSwitchStatus(this.selfinfoRecord);
		
		AutoLikerService alService = AutoLikerService.getInstance();
		if (alService != null) {
			if (alService.getTimerTask().isPause() == true) {
				this.swAutoLike.setChecked(false);
			} else {
				this.swAutoLike.setChecked(true);
			}
		}
		
	}
	
	@Override
	public void onFacebookCommandExecute(FacebookCommandObject fbco) {
		this.dlgLoading.show(this.getActivity().getSupportFragmentManager(), "Loading");
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		//super.onCreateView(inflater, container, savedInstanceState);
		
		MyLog.d(tag, "onCreateView()");
		
		AutoLikerService aService = AutoLikerService.getInstance();
		if (aService != null) {
			if (aService.getSelfInfo() != null) {
				this.selfinfoRecord = aService.getSelfInfo();
				MyLog.d(tag, "using self_info=" + this.selfinfoRecord.toString());
			}
		}

		if (this.getActivity() != null) {
			MyLog.d(tag, "Got context here!");
			if (this.context == null) {
				this.context = this.getActivity();
			}
		} else {
			MyLog.d(tag, "Even here, I cannot get context from this.getActivity()");
		}
		
		if (this.context != null) {
			this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			MyLog.d(tag, "context is not null, inflater is ready to be used");
		} else {
			MyLog.d(tag, "Cannot inflate layout, context is null");
		}
		
		this.root = (ViewGroup) inflater.inflate(R.layout.scrollview1, null);
		this.linearScroll = (LinearLayout) this.root.findViewById(R.id.linearScroll);
		this.vScrollView = (ScrollView) this.root.findViewById(R.id.vScrollView);
				
		this.tvName = (TextView) this.root.findViewById(R.id.tvName);
		this.tvUsername = (TextView) this.root.findViewById(R.id.tvUsername);
		this.imgSelfPhoto = (ImageView) this.root.findViewById(R.id.imgSelfPhoto);
		this.imgSelfPhoto.setOnClickListener(this);
		
		this.swLikeUpdateStatus = new MySwitcher(this.context, "like_update_status", this.selfinfoRecord, "Status Update", "");
		this.swLikeUpdatePhoto = new MySwitcher(context, "like_upload_photo", this.selfinfoRecord, "Upload Photo", "");
		this.swLikeSharePhoto = new MySwitcher(context, "like_share_photo", this.selfinfoRecord, "Share Photo", "");
		this.swLikeShareVideo = new MySwitcher(context, "like_share_video", this.selfinfoRecord, "Share Video", "");
		this.swLikeShareStory = new MySwitcher(context, "like_share_story", this.selfinfoRecord, "Share Story", "");
		this.swLikeTagPhoto = new MySwitcher(context, "like_tag_photo", this.selfinfoRecord, "Tag Photo", "");
		this.swLikeUploadVideo = new MySwitcher(context, "like_upload_video", this.selfinfoRecord, "Upload Video", "");
		this.swLikeChangeProfilePhoto = new MySwitcher(context, "like_change_profile_photo", this.selfinfoRecord, "Change Profile Photo", "");
		this.swLikeFromOther = new MySwitcher(context, "like_from_other", this.selfinfoRecord, "From Others", "");
		
		this.swAutoLike = (Switch) this.root.findViewById(R.id.swAutoLike);
		this.swAutoLike.setOnCheckedChangeListener(this);
		
		if (this.selfinfoRecord != null) {
			if (this.selfinfoRecord.timer_enable.equals("Y")) {
				this.swAutoLike.setChecked(true);
			} else {
				this.swAutoLike.setChecked(false);
			}
			
		} else {
			this.swAutoLike.setChecked(false);
		}
		
		
		linearScroll.addView(this.swLikeUpdateStatus.getView());
		linearScroll.addView(this.swLikeUpdatePhoto.getView());
		linearScroll.addView(this.swLikeSharePhoto.getView());
		linearScroll.addView(this.swLikeShareVideo.getView());
		linearScroll.addView(this.swLikeShareStory.getView());
		linearScroll.addView(this.swLikeTagPhoto.getView());
		linearScroll.addView(this.swLikeUploadVideo.getView());
		linearScroll.addView(this.swLikeChangeProfilePhoto.getView());
		linearScroll.addView(this.swLikeFromOther.getView());
				
		if (savedInstanceState != null) {
			int[] position = savedInstanceState.getIntArray("SCROLL_POSITION");
			final int x = position[0];
			final int y = position[1];
			
			//this.vScrollView.scrollTo(x, y);
			this.vScrollView.post(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					vScrollView.scrollTo(x, y);
				}
			});
			
			MyLog.d(tag, "can use savedInstacneState(x=" + x + ", y=" + y + ")");
		}
		
		MyLog.d(tag, "onCreateView() -- done");
		
		return(this.root);
	}

	@Override
	public void onClick(View v) {
		MyLog.d(tag, "onClick: " + v.getClass().getName());
		if (v == this.imgSelfPhoto) {
			//Intent intent = new Intent(this.getActivity(), com.tnsw.facebookautoliker.ConnectionProblemActivity.class);
			//this.getActivity().startActivityForResult(intent, 401);
			GetSelfInfo selfInfo = new GetSelfInfo(this.context);
			selfInfo.setParentFragmentBase(this);
			selfInfo.execute();
			
			/*
			 * DialogFragment dialog = new NoticeDialogFragment();
        	dialog.show(getSupportFragmentManager(), "NoticeDialogFragment");
			 */
			
			
		
		}
	}
	
	private void insertSelfInfo(GetSelfInfo self) {
		SelfInfo record = null;
				
		record = new SelfInfo();
				
		record.primarykey = 1;
		record.name = self.getName();
		record.email = self.getEmail();
		record.username = self.getUserName();
		record.lastupd = System.currentTimeMillis();
		record.id = self.getId();

		if (this.selfinfoRecord == null) {
			record.like_share_photo = "Y";
			record.like_share_story = "Y";
			record.like_share_video = "Y";
			record.like_tag_photo = "Y";
			record.like_update_status = "Y";
			record.like_upload_photo = "Y";
			record.like_upload_video = "Y";
			record.like_change_profile_photo = "Y";
			record.like_from_other = "Y";
			
			this.dbm.insertRecord("self_info", record, null, true);
			this.selfinfoRecord = record;
			
			AutoLikerService aService = AutoLikerService.getInstance();
			if (aService != null) {
				MyLog.d(tag, "first time run, just added self_info record and give reference to AutoLikerServices");
				aService.setSelfInfo(this.selfinfoRecord);
				
				this.swAutoLike.setChecked(true);
			}
			
		} else {
			MyLog.d(tag, "This condition should not happen");
			/*
			this.selfinfoRecord.name = self.getName();
			this.selfinfoRecord.email = self.getEmail();
			this.selfinfoRecord.username = self.getUserName();
			this.selfinfoRecord.lastupd = System.currentTimeMillis();
			this.selfinfoRecord.id = self.getId();
			
			if (this.selfinfoRecord.like_from_other == null) {
				this.selfinfoRecord.like_from_other = "Y";
			}
						
			this.dbm.updateRecordByPrimarykey("self_info", this.selfinfoRecord, true);
			*/
		}
		
		MyLog.d(tag, "insertSelfInfo - done");
	}

	@Override
	public void onRequestCompleted(Object sender, FacebookCommandObject fbco, int statusCode, Exception tr) {
		if (fbco instanceof GetSelfInfo) {
			
			MyLog.d(tag, "onRequestCompleted(" + fbco.getClass().getName() + ", statusCode=" + statusCode + ")");
			if (statusCode == 200) {
				GetSelfInfo self = (GetSelfInfo) fbco;
				this.tvUsername.setText(self.getUserName());
				this.tvName.setText(self.getName());
				
				String id = self.getId();
				String url = "https://graph.facebook.com/" + id + "/picture?width=300&height=300";
				Session session = Session.getActiveSession();
				if (session != null) {
					url = url + "&access_token=" + session.getAccessToken();
				}
				
				this.insertSelfInfo(self);
				this.updateSwitchesStatus();
				
				GetHTTPPhoto photo = new GetHTTPPhoto(context, url, id);
				photo.setTag("from", this.getClass().getName());
				photo.execute();	
			} else {
				if (this.dlgLoading != null) {
					
					this.dlgLoading.dismiss();	
					
						
				}
				
			}
			
			
		} else if (fbco instanceof GetHTTPPhoto) {
			GetHTTPPhoto photo = (GetHTTPPhoto) fbco;
			boolean isOwner = false;
			
			if (photo.getTag("from") == null) { 
				isOwner = false;
			
			} else {
				String from = (String) photo.getTag("from");
				if (from.equals(this.getClass().getName()) == true) isOwner = true;
			}
			
			
			if ( (statusCode == 200) && (isOwner == true) ) {
				
				MyLog.d(tag, "self_photo=" + photo.getPhotoPath());
				this.imgSelfPhoto.setImageBitmap(BitmapFactory.decodeFile(photo.getPhotoPath()));
				
				this.selfinfoRecord.photo_path = photo.getPhotoPath();
				this.dbm.updateRecordByPrimarykey("self_info", this.selfinfoRecord, true);	
				
			}
			
			if (this.dlgLoading != null) {
				if (this.dlgLoading.isAdded() == true) {
					this.dlgLoading.dismiss();
				}
				/*
				Activity a = (Activity) this.context;
				a.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						dlgLoading.dismiss();
						
					}
				});
				*/
			}
			
			this.setLastCommand(null);
			
		}
		
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		AutoLikerService alService = AutoLikerService.getInstance();
		
		if (alService != null) {
			if (isChecked == true) {
				if (alService.getTimerTask() != null) alService.getTimerTask().resume();
			} else {
				if (alService.getTimerTask() != null) alService.getTimerTask().pause();
			}	
		}
		
	}
	
	@Override
	public void onSaveInstanceState (Bundle outState) {
		super.onSaveInstanceState(outState);
		
		if (this.root != null) {
			int x, y;
			x = (int) this.vScrollView.getScrollX();
			y = (int) this.vScrollView.getScrollY();
						
			MyLog.d(tag, "saving(x=" + x + ", y=" + y + ")");
			outState.putIntArray("SCROLL_POSITION", new int[] {x, y});
			
		}

	}

}
